package com.jiangruan.javaproject.rpc;

import com.alibaba.fastjson.JSONObject;
import com.jiangruan.javaproject.Constants;
import com.jiangruan.javaproject.bean.PRCCommon;
import com.jiangruan.javaproject.request.HttpUtils;

import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * @author:zengguanlin
 * @email:zengguanlin@2977725281@qq.com
 * @desc:该类用于实现通过rpc访问调用bitcoin core的getbestblockhash功能
 * @datatime: 2021/12/21 15:32
 */
public class GetBestBlockHash {
    public static PRCCommon getBestBlockHash(){
        //准备rpc请求的用户身份信息
        String author = Constants.BITCOIN_RPC_USER+":"+Constants.BITCOIN_RPC_PWD;
        Base64.Encoder encoder = Base64.getEncoder();
        String authorBase64 = encoder.encodeToString(author.getBytes());
        //请求头的属性设置
        Map<String,String> header = new HashMap<>();
        header.put("ContentType","application/json");
        header.put("Authorization","Basic "+ authorBase64);

        //准备rpc请求的数据
        Map<String,Object> body = new HashMap<>();
        body.put("id",1001);
        body.put("method","getbestblockhash");
        body.put("params",null);
        body.put("json_rpc","2.0");

        //序列化
        byte[] bodyBytes = JSONObject.toJSONBytes(body);

        //发送请求
        //{"id":10001,"result":"xxx","error":null}
        String result = HttpUtils.post(Constants.BITCOIN_RPC_URL,header,bodyBytes);

        //反序列化
        PRCCommon prcCommon = JSONObject.parseObject(result, PRCCommon.class);

        return prcCommon;
    }
}